<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/12/6
 * Time: 12:18
 */

namespace Community\Model;


use Think\Model;

class GroupTableModel extends Model
{
    //自动验证
    protected $patchValidate = true;//开启批量验证
    protected $_validate = [
        ['name','require','名称不能为空'],
        ['phone','require','电话不能为空'],
        ['prise','currency','价格不合法'],
        ['phone','number','手机输入不合法'],
    ];
    //自动完成
    protected $_auto = [
        ['create_time','time',self::MODEL_INSERT,'function'],
        ['label','getRandString',self::MODEL_INSERT,'callback']
    ];
    protected function getRandString(){
        return substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'),0,10);
    }

    public function addGroup(){
        //获取当前用户信息
        $user_token = session('NOW_USER_TOKEN');
        $user_info = M('userdetail')->where(['token'=>$user_token])->find();
        if(!M('Doctor')->where(['user_id'=>$user_info['userid'],'status'=>'1'])->find()){
            $this->error = '您还没有经过医生审核，暂时不能操作';
            return false;
        }
        if(M('GroupTable')->where(['userid'=>$user_info['userid']])->find()){
            $this->error = '您已经创建过团队了，不能重复创建';
            return false;
        }
        $this->userid = $user_info['userid'];
        //获取数据
        $data = I('post.');
        //对自定义输入的技能进行分割
        $skills = $data['skill'];
        //将其它非因为逗号字符替换成英文逗号
        $skills = str_replace('，',',',$skills);
        $skills = str_replace('、',',',$skills);
        $skills = str_replace('。',',',$skills);
        $skills = str_replace(' ',',',$skills);
        $skills = trim($skills,',');//去掉两边得，
        $this->skill = $skills;
        $this->headurl = upload('group_img','B');
        $group_id = $this->add();
        if($group_id === false){
            $this->error = '提交失败，请重新提交';
            return false;
        }
        //将该用户得doctor表数据更新
        M('Doctor')->where(['user_id'=>$user_info['userid']])->save(['group_id'=>$group_id,'group_name'=>$data['name']]);
        //将该用户添加到成员表中
        M('group_member')->add(['userid'=>$user_info['userid'],'groupid'=>$group_id]);
        //将服务地区与地区表对应
        foreach ($data['server_are'] as $item){
            $shult[] = [
                'are_id'=>$item,
                'group_id'=>$group_id,
            ];
        }
        $shult ? M('group_serverare')->addAll($shult) : '';
        return true;
    }







}